<template>
	<view class="container">
		<view class="head-wrap">
			<view class="avatar-box">
				<image
					:src="userInfo.avatarUrl && userInfo.avatarUrl != 'url_to_default_avatar_image' ? userInfo.avatarUrl : '/static/mine/avatar.png'"
					mode="aspectFill"></image>
			</view>
			<view class="user-detail" @click="handleItemEvent({action:'editUserInfo'})">
				<view class="user-name">{{userInfo.userName || "还未设置用户名称"}}</view>
				<view class="edit-profile-btn">
					<text>编辑信息</text>
					<image src="/static/mine/right-arrow.png" mode="aspectFill"></image>
				</view>
			</view>
			<view class="card-box">
				<image src="/static/mine/card.png" mode="aspectFill"></image>
			</view>
		</view>
		<view class="page-body">
			<view class="assets-echart">
				<view class="wrap-title">总资产</view>
				<view class="money-row" @click="handleItemEvent({action:'changeUnit'})">
					<text class="money-value">{{accountConvert}}</text>
					<text class="money-unit">{{unit}}</text>
					<image src="/static/mine/jt-top.png" mode="aspectFill"></image>
				</view>

				<FeChart :option="assetsOption" idName="bitcoin_chart" height="306rpx"></FeChart>

				<view class="echart-tabs">
					<view class="tab-item" :class="echartFilterTab == 0 ? 'tab-active' : ''"
						@click="handleItemEvent({action:'echartTab',index:0,days:7})">7天</view>
					<view class="tab-item" :class="echartFilterTab == 1 ? 'tab-active' : ''"
						@click="handleItemEvent({action:'echartTab',index:1,days:30})">30天</view>
					<view class="tab-item" :class="echartFilterTab == 2 ? 'tab-active' : ''"
						@click="handleItemEvent({action:'echartTab',index:2,days:160})">160天</view>
					<view class="tab-item" :class="echartFilterTab == 3 ? 'tab-active' : ''"
						@click="handleItemEvent({action:'echartTab',index:3,days:340})">340天</view>
				</view>
			</view>
			<view class="money-package">
				<view class="left-package-wrap row-box-item">
					<view class="title">预充值余额</view>
					<view class="package-money-row">
						<text class="money-value">{{balanceValue}}</text>
						<text class="money-unit">USDT</text>
					</view>
					<view class="power-btn" @click="handleItemEvent({action:'buyIn'})">预充值管理</view>
				</view>
				<view class="right-package-wrap row-box-item">
					<view class="title">当前订单</view>
					<view class="package-money-row">
						<text class="money-value">{{userInfo && userInfo.orderCount ? userInfo.orderCount : 0}}</text>
						<text class="money-unit">个</text>
					</view>
					<view class="power-btn" @click="handleItemEvent({action:'allSell'})">所有账户一键平仓</view>
				</view>
			</view>
			<view class="accout-tip">
				<view class="tip-content" @click="$refs.explain.show('一键平仓')">
					<text>对一键平仓有疑问</text>
					<image src="/static/mine/wenhao.png" mode="aspectFill"></image>
				</view>
			</view>
			<view class="menu-list">
				<view class="menu-item" @click="handleItemEvent({action:'childMange'})">
					<image class="menu-icon" src="@/static/mine/zizhanghao.png" mode="aspectFill"></image>
					<text class="t1">子账号管理</text>
					<image class="menu-row-arrow" src="/static/mine/row-right.png" mode="aspectFill"></image>
				</view>
				<view class="menu-item" @click="handleItemEvent({action:'changeAccount'})">
					<image class="menu-icon" src="@/static/mine/qiehuan.png" mode="aspectFill"></image>
					<text class="t1">切换账号</text>
					<image class="menu-row-arrow" src="/static/mine/row-right.png" mode="aspectFill"></image>
				</view>
				<view class="menu-item" @click="handleUpgrade">
					<image class="menu-icon" src="@/static/mine/version.png" mode="aspectFill"></image>
					<view class="version-info">
						<text class="t1">当前版本号</text>
						<view class="version-desc" :style="/有新版本/.test(appNewVersionTip) ? 'color:red' : ''">
							{{appNewVersionTip || "您当前版本为最新版本"}}
						</view>
					</view>
					<view class="version-name">v{{versionName}}</view>
					<image class="menu-row-arrow" src="/static/mine/row-right.png" mode="aspectFill"></image>
				</view>
			</view>
		</view>

		<!-- 一键平仓 -->
		<onKeyClearPanel ref="refOnKeyClearPanel" @complete="handleClearComplete" />
		<Explain ref="explain" />
	</view>
</template>

<script>
	import FeChart from '@/components/FeChart/index.vue'
	import onKeyClearPanel from '@/components/onKeyClearPanel/onKeyClearPanel.vue'
	import Explain from '@/components/explain/explain.vue'

	// #ifdef APP-PLUS
	import APPUpdate from '@/uni_modules/zhouWei-APPUpdate/js_sdk/appUpdate';
	// #endif

	import {
		userProfile,
		userAssets,
		userAssetsRecords
	} from "@/api/user.js"
	import {
		balanceApi
	} from "@/api/prepaid.js"
	import {
		handleUpdateLocalAccount
	} from "@/common.js"

	export default {
		components: {
			FeChart,
			Explain,
			onKeyClearPanel
		},
		data() {
			return {
				versionName: getApp().globalData.appVersion.versionName, // 版本号
				appNewVersionTip: getApp().globalData.appNewVersionTip,
				userInfo: getApp().globalData.userInfo,
				echartFilterTab: 0,
				accountAssets: 0,
				accountConvert: 0,
				unit: 'USDT',
				assetsOption: {},
				balanceValue: 0,
				days: 7,
				rate: 1,
			};
		},
		onLoad() {
			uni.$on("needVersionUpdate", () => {
				this.appNewVersionTip = "有新版本";
			})
		},
		onUnload() {
			uni.$off("needVersionUpdate");
		},
		onShow() {
			const rates = uni.getStorageSync('rates')
			if (!this.isEmpty(rates)) {
				this.rate = rates[0].rate
			}

			if (this.islogin()) {
				this.reqUserProfile();
				this.getUserAssetsRecords();
				this.reqBalanceApi();
			} else {
				this.userInfo = {}
				this.accountAssets = 0;
				this.accountConvert = 0;
				this.balanceValue = 0;
				this.unit = 'USDT';
			}
		},
		watch: {
			unit: {
				handler(newVal) {
					if (!this.islogin()) return
					this.accountConvert = newVal == 'USDT' ? this.accountAssets : (this.accountAssets * this.rate).toFixed(
						2)
				}
			},
			accountAssets: {
				handler(newVal) {
					if (!this.islogin()) return
					this.accountConvert = this.unit == 'USDT' ? newVal : (newVal * this.rate).toFixed(2)
				}
			}
		},
		methods: {
			// 获取用户信息
			async reqUserProfile() {
				const result = await userProfile();

				const updateUserInfo = {
					...getApp().globalData.userInfo,
					...result.data
				}
				this.userInfo = {
					...updateUserInfo,
					...{}
				};
				uni.setStorageSync("userInfo", updateUserInfo);
				getApp().globalData.userInfo = updateUserInfo;

				handleUpdateLocalAccount({
					account_key: getApp().globalData.userInfo.email,
					fields_key: "avatarUrl",
					fields_value: updateUserInfo.avatarUrl
				})

				// 获取总资产
				const result2 = await userAssets();
				this.accountAssets = result2.data.asset || 0;
			},

			// 预充值余额
			async reqBalanceApi() {
				const result = await balanceApi();
				this.balanceValue = result.data.balance || 0;
			},

			handleItemEvent(vals) {
				const {
					action,
					index,
					days
				} = vals;

				if (!getApp().verifyIsLogin()) return

				switch (action) {
					case "editUserInfo": // 编辑用户信息
						this.toPages("/pages/tabbar/mine/userInfo");
						break;
					case "changeUnit": // 切换单位
						uni.showActionSheet({
							itemList: ["CNY", "USDT"],
							success: (res) => {
								this.unit = res.tapIndex ? 'USDT' : 'CNY';
							}
						})
						break;
					case "echartTab":
						this.echartFilterTab = index;
						this.days = days;
						this.getUserAssetsRecords();
						break;
					case "buyIn": // 买入
						this.toPages('/pages/tabbar/mine/prep');
						break;
					case "allSell": // 所有账户一键平仓
						if (this.userInfo.orderCount > 0) {
							this.$refs.refOnKeyClearPanel.show({
								level: "all"
							});
						} else {
							uni.showToast({
								title: '当前无订单可平仓',
								icon: 'none'
							})
						}
						break;
					case "sellDesc": // 一键平仓说明
						if (this.userInfo.orderCount > 0) {
							uni.showModal({
								title: "一键平仓",
								content: "将账户所有策略全部卖出",
								showCancel: false,
								confirmText: "知道了"
							})
						} else {
							uni.showToast({
								title: '当前无订单可平仓',
								icon: 'none'
							})
						}

						break;

					case "childMange": // 子账号管理
						this.toPages('/pages/tabbar/mine/subAccount/index');
						break

					case "changeAccount": // 切换账号
						this.toPages('/pages/tabbar/mine/accountDetail');
						break

				}
			},

			/**
			 * 获取个人总资产图表
			 */
			async getUserAssetsRecords() {
				const result = await userAssetsRecords({
					days: this.days
				});
				// result.data.returns = [{
				// 	date: "2024-04-12",
				// 	asset: 666
				// }, {
				// 	date: "2024-04-11",
				// 	asset: 143
				// }, {
				// 	date: "2024-04-10",
				// 	asset: -336005
				// }, {
				// 	date: "2024-04-9",
				// 	asset: 96
				// }, {
				// 	date: "2024-04-8",
				// 	asset: 63
				// }]
				const source = result.data.returns.reverse(); //前端倒序
				const seriesData = source.map(item => item.asset);

				this.$nextTick(() => {

					this.assetsOption = {
						tooltip: {
							trigger: 'axis',
							// axisPointer: {
							// 	type: 'line',
							// 	snap: true,
							// 	label: {
							// 		backgroundColor: '#6a7985'
							// 	}
							// }
							formatter: function(param) {
								const params = param[0];
								if (params.data >= 0) {
									return `<div>${params.name}</div><div>+$${params.data}</div>`;
								}
								return `<div>${params.name}</div><div>-$${Math.abs(params.data)}</div>`;
							},
						},
						grid: {
							top: uni.upx2px(30),
							left: uni.upx2px(30),
							bottom: uni.upx2px(32),
							right: uni.upx2px(30)
						},
						xAxis: {
							type: 'category',
							// 坐标轴两边留白策略，类目轴和非类目轴的设置和表现不一样。
							boundaryGap: false,
							data: source.length ? source.map(item => item.date.slice(5)) : [],
							// X坐标轴边框
							axisLine: {
								show: false
							},
							// X坐标轴刻度名称
							axisLabel: {
								show: false
							},
							// X坐标轴刻度
							axisTick: {
								show: false
							},
							// X坐标轴 标线
							splitLine: {
								show: false
							}
						},
						yAxis: {
							show: false,
							type: 'value',
							splitLine: {
								show: false
							}
						},
						series: [{
							data: source.length ? seriesData : [0, 0, 0, 0, 0, 0, 0],
							type: 'line',
							symbol: 'none',
							smooth: true,
							lineStyle: {
								color: "#FFE269",
								width: 1
							},
							areaStyle: {
								color: {
									type: 'linear',
									x: 0,
									y: 0,
									x2: 0,
									y2: 1,
									colorStops: [ // 渐变颜色
										{
											offset: 0,
											color: '#FFE269',
										},
										{
											offset: 1,
											color: 'rgba(255, 226, 105, 0.30)',
										},
									],
									global: false,
								},
							},
							markPoint: {
								data: [{
										type: 'max',
										name: 'max',
										itemStyle: {
											color: "rgba(255, 226, 105, 0)"
										},
										label: {
											// formatter: '+${c}',
											formatter: (vals) => {
												if (vals.value < 0) {
													return '-$' + `${Math.abs(vals.value)}`
												}
												return '+$' + vals.value
											},
											color: '#D6A909',
											fontSize: uni.upx2px(24),
											fontWeight: 500,
											offset: [10, 20],
										}
									},
									{
										type: 'min',
										name: 'Min',
										itemStyle: {
											color: "rgba(255, 226, 105, 0)"
										},
										label: {
											// formatter: '+${c}',
											formatter: (vals) => {
												if (vals.value < 0) {
													return '-$' + `${Math.abs(vals.value)}`
												}
												return '+$' + vals.value
											},
											color: '#D6A909',
											fontSize: uni.upx2px(24),
											fontWeight: 500,
											offset: [10, 0],
											position: 'bottom'
										}
									}
								]
							},
							// markLine: {
							// 	label: {
							// 		show: false
							// 	},
							// 	data: [{
							// 		xAxis: source.length - 1
							// 	}]
							// },
						}]
					}
				})
			},

			handleClearComplete() {
				this.reqUserProfile();
				this.getUserAssetsRecords();
				this.reqBalanceApi();
			},

			// 检查APP是否有新版本
			handleUpgrade() {
				// #ifdef APP-PLUS
				// true 在出现无新版本的情况下，有弹窗提示
				// false 无提示（一般在APP.vue使用）
				uni.showLoading({
					title: "获取中...",
					mask: true
				})
				APPUpdate(true);
				// #endif

				// #ifndef APP-PLUS
				uni.showToast({
					title: "请在APP环境使用",
					icon: "none"
				});
				// #endif
			},

		}
	}
</script>

<style scoped lang="scss">
	.container {
		width: 100vw;
		min-height: 100vh;
		background-color: #F5F7F8;

		.head-wrap {
			height: 388rpx;
			background-color: #FFE269;
			display: flex;
			align-items: center;
			padding-left: 32rpx;
			position: relative;

			.avatar-box {
				width: 110rpx;
				height: 110rpx;
				background-color: #eeeeee;
				border-radius: 50%;
				overflow: hidden;

				image {
					width: 100%;
					height: 100%;
				}
			}

			.user-detail {
				margin-left: 32rpx;

				.user-name {
					font-size: 32rpx;
					color: #26282B;
					font-weight: 600;
					line-height: 38rpx;
					padding-bottom: 14rpx;
				}

				.edit-profile-btn {
					font-size: 24rpx;
					color: #A77E15;
					display: flex;
					align-items: center;

					image {
						width: 24rpx;
						height: 24rpx;
					}
				}
			}

			.card-box {
				width: 264rpx;
				height: 228rpx;
				position: absolute;
				right: 0;
				bottom: 0;

				image {
					width: 100%;
					height: 100%;
				}
			}
		}

		.page-body {
			padding: 0 32rpx;
			position: relative;
			top: -82rpx;

			.assets-echart {
				background-color: #ffffff;
				border-radius: 12rpx;
				margin-bottom: 24rpx;
				min-height: 540rpx;
				padding: 40rpx 0rpx;

				.wrap-title {
					font-size: 30rpx;
					color: #26282B;
					font-weight: 600;
					line-height: 35rpx;
					padding: 0 30rpx;
					padding-bottom: 8rpx;
				}

				.money-row {
					color: #26282B;
					font-weight: bold;
					margin-bottom: 0rpx;
					display: inline-block;
					line-height: 70rpx;
					padding: 0 30rpx;

					.money-value {
						font-size: 60rpx;
						line-height: 54rpx;
					}

					.money-unit {
						line-height: 28rpx;
						font-size: 30rpx;
						margin: 0 8rpx;
					}

					image {
						width: 24rpx;
						height: 24rpx;
					}
				}

				.echart-load {
					height: 248rpx;
					line-height: 248rpx;
					text-align: center;
					font-size: 28rpx;
					color: #999;
				}

				.echart-tabs {
					display: flex;
					align-items: center;
					justify-content: space-between;
					padding: 0 30rpx;

					.tab-item {
						width: 104rpx;
						height: 48rpx;
						line-height: 48rpx;
						background-color: #EEF1F6;
						font-size: 24rpx;
						color: #7B828A;
						text-align: center;
						border-radius: 8rpx;
					}

					.tab-active {
						background-color: #FFE269;
						color: #26282B;
					}
				}
			}

			.money-package {
				min-height: 222rpx;
				display: flex;
				justify-content: space-between;

				.row-box-item {
					flex: 1;
					border-radius: 12rpx;
					padding: 32rpx 0 32rpx 30rpx;

					.title {
						font-size: 26rpx;
						color: #7B828A;
						line-height: 30rpx;
					}

					.package-money-row {
						color: #26282B;
						font-weight: bold;
						flex: 1;
						text-align: left;
						padding: 12rpx 0 28rpx 0;

						.money-value {
							font-size: 44rpx;
							margin-right: 8rpx;
							line-height: 52rpx;
							word-break: break-all;
						}

						.money-unit {
							font-size: 26rpx;
							line-height: 30rpx;
						}
					}

					.power-btn {
						width: 270rpx;
						height: 72rpx;
						line-height: 72rpx;
						border-radius: 8rpx;
						font-size: 28rpx;
						text-align: center;
					}
				}

				.left-package-wrap {
					background: linear-gradient(149deg, #EBFFF8 0%, #FFFFFF 100%);
					margin-right: 13rpx;

					.power-btn {
						background-color: #63D0A8;
						color: #ffffff;
					}
				}

				.right-package-wrap {
					background: linear-gradient(149deg, #FFFDEC 0%, #FFFFFF 100%);
					margin-left: 13rpx;

					.power-btn {
						background-color: #FFE269;
						color: #26282B;
					}
				}
			}

			.accout-tip {
				font-size: 24rpx;
				color: #A6ACB4;
				line-height: 28rpx;
				display: flex;
				align-items: center;
				justify-content: flex-end;
				margin: 24rpx 0;

				.tip-content {
					display: flex;
					align-items: center;
					justify-content: flex-end;

					image {
						width: 26rpx;
						height: 26rpx;
						margin-left: 8rpx;
					}
				}
			}

			.menu-list {
				background-color: #FFFFFF;
				border-radius: 12rpx;

				.menu-item {
					height: 116rpx;
					padding: 0 30rpx;
					display: flex;
					align-items: center;

					.version-info {
						flex: 1;
						margin: 0 auto 0 0;

						.version-desc {
							font-size: 24rpx;
							color: #999;
						}
					}

					.menu-icon {
						width: 36rpx;
						height: 36rpx;
						margin-right: 20rpx;
					}

					.t1 {
						font-size: 30rpx;
						font-weight: 400;
						color: #26282B;
						flex: 1;
					}

					.menu-row-arrow {
						width: 24rpx;
						height: 24rpx;
					}

					.version-name {
						color: #A6ACB4;
						margin-right: 20rpx;
					}
				}
			}
		}
	}
</style>